package com.cfweb.api;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cfweb.controller.LoginHandler;
import com.cfweb.util.CloudFoundryClientUtil;
import com.cfweb.util.JsonUtil;

public class OrgApi {

	static Logger logger = Logger.getLogger(OrgApi.class);

	/**
	 * create an org
	 * 
	 * @param orgName
	 * @param session
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean create_org(HttpSession session, final String orgName, final String quotaGuid)
			throws Exception {
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/organizations";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name", orgName);
			params.put("quota_definition_guid", quotaGuid);
			CloudFoundryClientUtil.doCCPost(urlPath, params, session);
		} catch (Exception e) {
			throw e;
		}
		return true;
	}

	/**
	 * delete an org
	 * 
	 * @param orgName
	 * @param session
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean delete_org(HttpSession session, String orgName) throws Exception {
		String orgId;
		orgId = UserApi.get_org_id(session, orgName);
		if (orgId.isEmpty()) {
			return false;
		}
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/organizations/" + orgId + "?async=false&recursive=true";

			String content = CloudFoundryClientUtil.doCCDelete(urlPath, null, session);
		} catch (Exception e) {
			throw e;

		}
		return true;
	}

	/**
	 * rename an org
	 * 
	 * @param orgName
	 * @param newName
	 * @param session
	 * @return boolean
	 * @throws Exception
	 */
	public static boolean rename_org(HttpSession session, String orgName, String newName) throws Exception {
		String orgId;
		orgId = UserApi.get_org_id(session, orgName);
		if (orgId.isEmpty()) {
			return false;
		}
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/organizations/" + orgId;
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name", newName);
			String content = CloudFoundryClientUtil.doCCPut(urlPath, params, session);
		} catch (Exception e) {
			throw e;
		}
		return true;
	}

	public static boolean update_org(HttpSession session, String orgName, String newName, String quotaGuid)
			throws Exception {
		String orgId;
		orgId = UserApi.get_org_id(session, orgName);
		if (orgId.isEmpty()) {
			return false;
		}
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/organizations/" + orgId;
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name", newName);
			params.put("quota_definition_guid", quotaGuid);
			CloudFoundryClientUtil.doCCPut(urlPath, params, session);
		} catch (Exception e) {
			throw e;
		}
		return true;
	}

	public static boolean setQuota(HttpSession session, String orgName, String quotaGuid) throws Exception {
		String orgId;
		orgId = UserApi.get_org_id(session, orgName);
		if (orgId.isEmpty()) {
			return false;
		}
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/organizations/" + orgId;
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("quota_definition_guid", quotaGuid);
			CloudFoundryClientUtil.doCCPut(urlPath, params, session);
		} catch (Exception e) {
			throw e;
		}
		return true;
	}

	/**
	 * list all of orgs
	 * 
	 * @param orgName
	 * @param newName
	 * @param session
	 * @return List<Map<String, Object>>
	 * @throws Exception
	 */

	@SuppressWarnings("unchecked")
	public static List<Map<String, Object>> list_orgs(HttpSession session) throws Exception {
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/organizations";
			String content = CloudFoundryClientUtil.doCCGet(urlPath, null, session);
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			List<Map<String, Object>> lr = (List<Map<String, Object>>) data.get("resources");
			String next_url = (String) data.get("next_url");
			while (next_url != null) {
				next_url = ApiCommonUtil.retriveAllPageResource(lr, next_url, session);
			}
			for (Map<String, Object> r : lr) {
				Map<String, Object> tmp = new HashMap<String, Object>();
				Map<String, Object> metadata = (Map<String, Object>) r.get("metadata");
				String guid = (String) metadata.get("guid");
				Map<String, Object> entity = (Map<String, Object>) r.get("entity");
				String orgName = (String) entity.get("name");
				tmp.put("guid", guid);
				tmp.put("name", orgName);
				tmp.put("quota", entity.get("quota_definition_guid"));
				res.add(tmp);
			}
			// String content = EntityUtils.toString(returnEntity, "UTF-8");
		} catch (Exception e) {
			throw e;
		}
		return res;
	}

	/**
	 * get detail of an org
	 * 
	 * @param orgName
	 * @param session
	 * @return List<Map<String, Object>>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static List<Map<String, Object>> list_org(HttpSession session, final String orgName) throws Exception {

		String orgId = null;
		orgId = UserApi.get_org_id(session, orgName);
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/organizations/" + orgId;

			String content = CloudFoundryClientUtil.doCCGet(urlPath, null, session);
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);

			Map<String, Object> tmp = new HashMap<String, Object>();
			Map<String, Object> metadata = (Map<String, Object>) data.get("metadata");
			String guid = (String) metadata.get("guid");
			tmp.put("guid", guid);
			tmp.put("name", orgName);
			res.add(tmp);

		} catch (Exception e) {
			throw e;
		}
		return res;
	}

	/**
	 * get quota of an org
	 * 
	 * @param orgName
	 * @param session
	 * @return Map<String, Object>
	 * @throws Exception
	 */
	public static Map<String, Object> getOrgQuota(String orgName, HttpSession session) throws Exception {
		String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
		String urlPath = host + "/v2/quota_definitions";
		if (orgName != null) {
			urlPath = urlPath + "?q=name:" + orgName;
		}
		String content = CloudFoundryClientUtil.doCCGet(urlPath, null, session);
		Map<String, Object> data = JsonUtil.convertJsonToMap(content);
		List<Map<String, Object>> resources = (List<Map<String, Object>>) data.get("resources");
		if (resources.size() > 0) {
			return (Map<String, Object>) ((Map<String, Object>) resources).get(0);
		}
		return null;
	}

	/**
	 * get particular org
	 * 
	 * @param orgName
	 * @param session
	 * @return Map<String, Object>
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getParticularOrg(String orgName, HttpSession session) throws Exception {
		String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
		String urlPath = host + "/v2/organizations?q=name%3A" + orgName + "&inline-relations-depth=1";
		String content = CloudFoundryClientUtil.doCCGet(urlPath, null, session);
		Map<String, Object> data = JsonUtil.convertJsonToMap(content);
		if ((int) data.get("total_results") == 0) {
			return null;
		}
		return ((List<Map<String, Object>>) data.get("resources")).get(0);
	}

	/**
	 * 
	 * @param session
	 * @param orgName
	 * @param quotaId
	 * @return
	 * @throws Exception
	 */
	public static boolean setOrgQuota(HttpSession session, String orgName, String quotaId) throws Exception {
		String orgId;
		orgId = UserApi.get_org_id(session, orgName);
		if (orgId.isEmpty()) {
			return false;
		}
		try {
			String host = ((URL) session.getAttribute(LoginHandler.TARGET)).toString();
			String urlPath = host + "/v2/organizations/" + orgId;
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("quota_definition_guid", quotaId);
			CloudFoundryClientUtil.doCCPut(urlPath, params, session);
		} catch (Exception e) {
			throw e;
		}
		return true;
	}

}
